import { defineStore } from "pinia";
import { ref } from "vue";
export const usePermissionStore = defineStore(
  "permission",
  () => {
    const permissionsList = ref<string[]>([]);
    function setPermissionsList(newPermissionsList: string[]) {
      permissionsList.value = newPermissionsList;
    }
    // 校验权限
    function hasPermission(permission: any): boolean {
      const currentUser = useCurrentUserStore().currentUser;
      if (currentUser.ifSuperAdmin) return true;
      if (permissionsList.value.includes("all")) return true;
      if (!permission) return true;
      // 字符串类型
      if (typeof permission === "string") {
        return permissionsList.value.includes(permission);
      }
      // 数组类型
      if (Array.isArray(permission)) {
        return permission.some((p) => permissionsList.value.includes(p));
      }
      // 函数类型
      if (typeof permission === "function") {
        return permission(permissionsList.value);
      }
      return false;
    }
    return {
      permissionsList,
      setPermissionsList,
      hasPermission,
    };
  },
  {
    // 默认持久化在 cookie 中
    persist: true,
  }
);
